package pt.ua.miect.sd.simuladorpesca.entities;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import org.apache.log4j.Logger;

/**
 * Manages the radio messages between boats on the fleet and Companies
 * @author PedroA
 *
 */
public class FleetMessageBox {

    private ConcurrentHashMap<String, LinkedBlockingQueue<RadioMessage>> messageBox;
    private static FleetMessageBox singleton;
    private Semaphore semaphore;

    private FleetMessageBox() {
        messageBox = new ConcurrentHashMap<String, LinkedBlockingQueue<RadioMessage>>();
        semaphore = new Semaphore(1);
    }

    /**
     * Gets the instance of the class
     * @return
     */
    public synchronized static FleetMessageBox getInstance() {
        if (singleton == null) {
            singleton = new FleetMessageBox();
        }
        return singleton;
    }

    /**
     * Gets the first message in queue for the target receiver
     * @param receiver
     * @return
     */
    public  RadioMessage getRadioMessage(String receiver) {
        try {
            //tests if the receiver is registered on the messageBox
            RadioMessage msg;
            semaphore.acquire();
            if (!messageBox.containsKey(receiver)) {
              //  messageBox.put(receiver, new LinkedBlockingQueue<RadioMessage>());
                msg = null;
            }else{
            msg = messageBox.get(receiver).poll();
            }
            semaphore.release();
            return msg;
        } catch (InterruptedException ex) {
            Logger.getLogger(FleetMessageBox.class).error(ex);
            return null;
        }
    }

    /**
     * Sets a new radio message
     * @param receiver
     * @param msg
     */
    public   void setRadioMessage( RadioMessage msg) {
        try {
            semaphore.acquire();
            String receiver = msg.getReceiverID();
            if (!messageBox.containsKey(receiver)) {
                messageBox.put(receiver, new LinkedBlockingQueue<RadioMessage>());
            }
            messageBox.get(receiver).add(msg);
            semaphore.release();
        } catch (InterruptedException ex) {
             Logger.getLogger(FleetMessageBox.class).error(ex);
        }
    }
}
